import moment from 'moment';
import * as util from '../../../util';
import log from '../../../log';
import * as data from './data';
import * as queTempCore from '../queTemplate/core';
import * as queCore from '../que/core';

// eslint-disable-next-line
function saveAnswers(user, queTempId, questions, status) {
    //判断是否结束
    return queTempCore.find({id: queTempId}).then(queTemp => {
        queTemp = queTemp[0] || [];
        return queCore.find({queTempId, createUserId: user.id}).then(_que => {
            _que = _que || [];
            if (_que.length > 0) {
                throw '已经回答过此问卷';
            }
            if (moment(queTemp.dateEnd) < moment()) {
                throw '问卷已过期，不能回答';
            }
            //目前只有一个问题
            if (queTemp.questions[0].max < questions[0].options.length) {
                throw '回答选项超过最大数量限制';
            }
            //是否超过最大选择数据限制

            const que = {};
            const now = moment().format('YYYY-MM-DD HH:mm:ss');
            que.id = util.uuid();
            que.createUserId = user.id;
            que.createUserName = user.name;
            que.createTime = now;
            que.status = status || 3;
            que.queTempId = queTempId;
            que.submitTime = now;
            log.info('add que  parms----', que);

            log.info(`保存用户[${user.name}]回答的问卷模板${queTempId} 生成问卷 ${que.id}`);

            const answers = [];
            questions.forEach(q => {
                q.options.forEach(oId => {
                    answers.push({
                        id: util.uuid(),
                        queId: que.id,
                        questionId: q.id,
                        optionId: oId,
                        userId: user.id
                    });
                });
            });

            return data.saveAnswers(que, answers);
        });
    });
}

function getAnswers(queId) {
    log.info(`获取问卷任务${queId}的答案`);
    return data.getAnswers(queId);
}

export {saveAnswers, getAnswers};
